<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>你画我猜 - AI版</title>
    <style>
      body {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20px;
        font-family: Arial, sans-serif;
        background-color: #f5f5f5;
        min-height: 100vh;
        margin: 0;
      }

      .container {
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
        width: 95%;
        max-width: 800px;
      }

      .game-title {
        font-size: clamp(20px, 5vw, 24px);
        color: #333;
        margin-bottom: 20px;
        text-align: center;
      }

      .game-description {
        color: #666;
        margin-bottom: 20px;
        text-align: center;
        font-size: clamp(14px, 3vw, 16px);
      }

      canvas {
        border: 1px solid #000;
        background: white;
        max-width: 100%;
        height: auto;
      }

      .controls {
        margin: 20px 0;
        display: flex;
        gap: 10px;
        align-items: center;
        justify-content: center;
        flex-wrap: wrap;
      }

      .controls button {
        padding: clamp(6px, 2vw, 8px) clamp(12px, 3vw, 16px);
        font-size: clamp(14px, 3vw, 16px);
        cursor: pointer;
        background: #4caf50;
        color: white;
        border: none;
        border-radius: 4px;
        transition: all 0.3s;
        white-space: nowrap;
      }

      .controls button:hover {
        background: #45a049;
        transform: translateY(-2px);
      }

      .controls button.active {
        background: #f44336;
      }

      .controls button:disabled {
        background: #cccccc;
        cursor: not-allowed;
        transform: none;
      }

      .loading {
        position: relative;
        opacity: 0.7;
      }

      .loading::after {
        content: 'AI正在思考...';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 15px 30px;
        border-radius: 8px;
        font-size: clamp(14px, 3vw, 18px);
      }

      .tool-group {
        display: flex;
        align-items: center;
        gap: 10px;
        flex-wrap: wrap;
        justify-content: center;
      }

      input[type='color'] {
        width: clamp(30px, 8vw, 40px);
        height: clamp(30px, 8vw, 40px);
        padding: 0;
        border: none;
        border-radius: 4px;
        cursor: pointer;
      }

      input[type='range'] {
        width: clamp(80px, 20vw, 100px);
      }

      footer {
        text-align: center;
        padding: 20px;
        color: #666;
        font-size: clamp(12px, 2.5vw, 14px);
        width: 100%;
        max-width: 800px;
      }

      @media (max-width: 600px) {
        .container {
          padding: 15px;
        }

        .controls {
          flex-direction: column;
          align-items: stretch;
        }

        .tool-group {
          flex-direction: row;
          justify-content: center;
        }

        .controls button {
          width: 100%;
        }
      }

      @media (max-width: 400px) {
        body {
          padding: 10px;
        }

        .container {
          padding: 10px;
        }

        .tool-group {
          gap: 5px;
        }
      }
    </style>
  </head>

  <body>
    <div class="container">
      <h1 class="game-title">你画我猜 - AI版</h1>
      <p class="game-description">
        在画布上绘制任何内容，让AI来猜测你画的是什么！
      </p>

      <div class="controls">
        <div class="tool-group">
          <button type="button" id="clearBtn">清除画布</button>
          <button type="button" id="eraserBtn">橡皮擦</button>
          <input type="color" id="colorPicker" value="#000000" />
          <input type="range" id="lineWidth" min="1" max="20" value="2" />
        </div>
        <button type="button" id="recognizeBtn">让AI猜一猜</button>
        <button type="button" id="downloadBtn">保存绘画</button>
      </div>

      <canvas id="drawingCanvas" width="800" height="600"></canvas>
    </div>

    <footer>
      <p>免责申明：本网站提供的绘画功能仅供娱乐，不承担任何法律责任。</p>
    </footer>
    <script>
      const canvas = document.getElementById('drawingCanvas');
      const ctx = canvas.getContext('2d');
      const recognizeBtn = document.getElementById('recognizeBtn');
      const clearBtn = document.getElementById('clearBtn');
      const downloadBtn = document.getElementById('downloadBtn');
      const eraserBtn = document.getElementById('eraserBtn');
      const colorPicker = document.getElementById('colorPicker');
      const lineWidth = document.getElementById('lineWidth');

      let isDrawing = false;
      let lastX = 0;
      let lastY = 0;
      let isEraser = false;
      let currentColor = '#000000';

      // 设置画布尺寸
      function setupCanvas() {
        // 固定画布的显示尺寸
        canvas.style.width = '800px';
        canvas.style.height = '600px';
        
        // 设置画布的实际尺寸
        canvas.width = 800;
        canvas.height = 600;

        // 重置画布样式
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';
        ctx.strokeStyle = currentColor;
        ctx.lineWidth = 2;
      }

      // 获取鼠标/触摸在画布上的位置
      function getCanvasPosition(e) {
        const rect = canvas.getBoundingClientRect();
        const scaleX = canvas.width / rect.width;
        const scaleY = canvas.height / rect.height;
        
        let clientX, clientY;
        
        // 处理触摸事件
        if (e.touches && e.touches[0]) {
          clientX = e.touches[0].clientX;
          clientY = e.touches[0].clientY;
        } else {
          clientX = e.clientX;
          clientY = e.clientY;
        }

        return {
          x: (clientX - rect.left) * scaleX,
          y: (clientY - rect.top) * scaleY
        };
      }

      // 初始化画布设置
      setupCanvas();

      // 事件监听器
      clearBtn.addEventListener('click', clearCanvas);
      recognizeBtn.addEventListener('click', handleRecognize);
      downloadBtn.addEventListener('click', downloadDrawing);
      eraserBtn.addEventListener('click', toggleEraser);
      colorPicker.addEventListener('change', handleColorChange);
      lineWidth.addEventListener('input', handleLineWidthChange);

      // 鼠标事件监听
      canvas.addEventListener('mousedown', handleStart);
      canvas.addEventListener('mousemove', handleMove);
      canvas.addEventListener('mouseup', stopDrawing);
      canvas.addEventListener('mouseout', stopDrawing);

      // 触摸事件监听
      canvas.addEventListener('touchstart', handleStart, { passive: false });
      canvas.addEventListener('touchmove', handleMove, { passive: false });
      canvas.addEventListener('touchend', stopDrawing);
      canvas.addEventListener('touchcancel', stopDrawing);

      function handleStart(e) {
        e.preventDefault();
        const pos = getCanvasPosition(e);
        isDrawing = true;
        [lastX, lastY] = [pos.x, pos.y];
      }

      function handleMove(e) {
        if (!isDrawing) return;
        e.preventDefault();
        const pos = getCanvasPosition(e);

        if (isEraser) {
          const radius = ctx.lineWidth;
          ctx.save();
          ctx.globalCompositeOperation = 'destination-out';
          ctx.beginPath();
          ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);
          ctx.fill();
          ctx.restore();
        } else {
          ctx.beginPath();
          ctx.moveTo(lastX, lastY);
          ctx.lineTo(pos.x, pos.y);
          ctx.stroke();
        }

        [lastX, lastY] = [pos.x, pos.y];
      }

      function stopDrawing() {
        isDrawing = false;
      }

      function clearCanvas() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
      }

      function toggleEraser() {
        isEraser = !isEraser;
        eraserBtn.classList.toggle('active');
        updateCursor();
      }

      function handleColorChange(e) {
        currentColor = e.target.value;
        if (!isEraser) {
          ctx.strokeStyle = currentColor;
        }
        updateCursor();
      }

      function handleLineWidthChange(e) {
        ctx.lineWidth = e.target.value;
        updateCursor();
      }

      function updateCursor() {
        const radius = ctx.lineWidth;
        const center = radius + 2;
        let svg;
        if (isEraser) {
          svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${center * 2}" height="${center * 2}" viewBox="0 0 ${center * 2} ${center * 2}"><circle cx="${center}" cy="${center}" r="${radius}" fill="none" stroke="red" stroke-width="2"/></svg>`;
        } else {
          svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${center * 2}" height="${center * 2}" viewBox="0 0 ${center * 2} ${center * 2}"><circle cx="${center}" cy="${center}" r="${radius}" fill="none" stroke="black" stroke-width="2"/></svg>`;
        }
        const cursorUrl = `url('data:image/svg+xml;utf8,${encodeURIComponent(svg)}') ${center} ${center}, auto`;
        canvas.style.cursor = cursorUrl;
      }

      function setLoading(loading) {
        recognizeBtn.disabled = loading;
        if (loading) {
          canvas.classList.add('loading');
        } else {
          canvas.classList.remove('loading');
        }
      }

      function saveCanvasAsJPG() {
        const tempCanvas = document.createElement('canvas');
        tempCanvas.width = canvas.width;
        tempCanvas.height = canvas.height;
        const tempCtx = tempCanvas.getContext('2d');

        // 先填充白色背景
        tempCtx.fillStyle = 'white';
        tempCtx.fillRect(0, 0, tempCanvas.width, tempCanvas.height);

        // 再绘制原始画布内容
        tempCtx.drawImage(canvas, 0, 0);

        return tempCanvas.toDataURL('image/jpeg', 0.9);
      }

      function downloadDrawing() {
        if (isCanvasEmpty()) {
          alert('请先在画布上绘制内容');
          return;
        }

        const link = document.createElement('a');
        link.download = `我的绘画_${new Date().toISOString().slice(0, 10)}.jpg`;
        link.href = saveCanvasAsJPG();
        link.click();
      }

      async function handleRecognize(event) {
        // 检查画布是否为空
        const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        const pixels = imageData.data;
        const hasDrawing = pixels.some((pixel) => pixel !== 0);

        if (!hasDrawing) {
          alert('请先在画布上绘制内容！');
          return;
        }

        try {
          // 获取当前页面的基础URL
          const baseUrl =
            window.location.protocol + '//' + window.location.host;

          const imageDataWithBackground = saveCanvasAsJPG();

          // 请求配置
          const requestOptions = {
            method: 'POST',
            headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              image: imageDataWithBackground,
            }),
            credentials: 'same-origin',
          };

          // 发送请求并等待响应
          const response = await fetch(
            baseUrl + '/api/image-recognition',
            requestOptions,
          );

          // 检查响应状态
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }

          // 验证响应类型
          const contentType = response.headers.get('content-type');
          if (!contentType || !contentType.includes('application/json')) {
            throw new TypeError('返回的数据格式不正确!');
          }

          const data = await response.json();

          if (!data || !data.result) {
            throw new Error('返回数据格式错误');
          }

          // 发送POST请求到结果页面
          const resultForm = document.createElement('form');
          resultForm.method = 'POST';
          resultForm.action = '/api/result';

          // 添加识别结果
          const resultInput = document.createElement('input');
          resultInput.type = 'hidden';
          resultInput.name = 'result';
          resultInput.value = data.result;
          resultForm.appendChild(resultInput);

          // 添加图片数据
          const imageInput = document.createElement('input');
          imageInput.type = 'hidden';
          imageInput.name = 'image';
          imageInput.value = imageDataWithBackground;
          resultForm.appendChild(imageInput);

          // 添加到页面并提交
          document.body.appendChild(resultForm);
          resultForm.submit();
        } catch (error) {
          let errorMessage = '抱歉，识别过程出现错误。';
          if (error.name === 'AbortError') {
            errorMessage = '请求超时，请稍后重试。';
          } else if (error instanceof TypeError) {
            errorMessage =
              error.message === 'Failed to fetch'
                ? '无法连接到服务器，请确保服务器已启动'
                : '数据格式错误，请重试。';
          }

          alert(errorMessage);
        }
      }

      function isCanvasEmpty() {
        const pixelBuffer = new Uint32Array(
          ctx.getImageData(0, 0, canvas.width, canvas.height).data.buffer,
        );
        return !pixelBuffer.some((color) => color !== 0);
      }

      // 初始化光标
      updateCursor();
    </script>
  </body>
</html>
